package io.renren.modules.practice.controller;

import io.renren.common.utils.R;
import io.renren.modules.practice.entity.PythonQuizEntity;
import io.renren.modules.practice.entity.dto.PythonSubmitDto;
import io.renren.modules.practice.service.PythonPracticeService;
import io.renren.modules.learn.entity.PythonChapterEntity;
import io.renren.modules.learn.service.PythonChapterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/practice/basic")
public class PythonPracticeController {

    @Autowired
    private PythonPracticeService pythonPracticeService;

    @Autowired
    private PythonChapterService pythonChapterService;

    /**
     * 根据题目ID获取题目详情
     */
    @GetMapping("/quiz/{quizId}")
    public R getQuizById(@PathVariable("quizId") Integer quizId) {
        try {
            PythonQuizEntity quiz = pythonPracticeService.getQuizById(quizId);
            if (quiz == null) {
                return R.error("题目不存在");
            }
            return R.ok().put("data", quiz);
        } catch (Exception e) {
            log.error("获取Python题目详情异常: {}", e.getMessage(), e);
            return R.error("获取题目详情失败");
        }
    }

    /**
     * 获取所有章节列表
     */
    @GetMapping("/chapters")
    public R getChapters() {
        try {
            List<PythonChapterEntity> chapters = pythonChapterService.getAllChapters();
            return R.ok().put("data", chapters);
        } catch (Exception e) {
            log.error("获取章节列表异常: {}", e.getMessage(), e);
            return R.error("获取章节列表失败");
        }
    }

    /**
     * 获取Python基础知识题目列表，支持按章节ID查询
     */
    @GetMapping("/list")
    public R getBasicQuizList(@RequestParam(value = "chapterId", required = false) Integer chapterId) {
        try {
            Integer cid = chapterId != null ? chapterId : 1;
            List<PythonQuizEntity> quizList = pythonPracticeService.getQuizListByChapterId(cid);
            return R.ok().put("data", quizList);
        } catch (Exception e) {
            log.error("获取Python基础知识题目列表异常: {}", e.getMessage(), e);
            return R.error("获取基础知识题目列表失败");
        }
    }

    /**
     * 提交Python基础题目答案，返回pass和explanation
     */
    @PostMapping("/quiz/submit")
    public R submitBasicQuiz(@RequestBody PythonSubmitDto submitDto) {
        try {
            PythonQuizEntity quiz = pythonPracticeService.getQuizById(submitDto.getQuizId());
            if (quiz == null) {
                return R.error("题目不存在");
            }
            boolean isCorrect = quiz.getCorrectAnswer().equals(submitDto.getSelectedAnswer());
            return R.ok().put("pass", isCorrect).put("explanation", quiz.getExplanation());
        } catch (Exception e) {
            log.error("基础题目提交异常: {}", e.getMessage(), e);
            return R.error("提交失败: " + e.getMessage());
        }
    }
} 